package com.ds.infra.mq.example;

import com.ds.infra.mq.core.api.MQProducer;
import com.ds.infra.mq.core.api.Producer;

import java.util.Scanner;

public class ProducerExampleV2 {
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter broker host (default: localhost):");
        String host = scanner.nextLine().trim();
        if (host.isEmpty()) host = "localhost";

        System.out.println("Enter broker port (default: 9092):");
        int port = 9092;
        try {
            String portStr = scanner.nextLine().trim();
            if (!portStr.isEmpty()) port = Integer.parseInt(portStr);
        } catch (NumberFormatException e) {
            System.out.println("Invalid port, using default 9092");
        }

        System.out.println("Enter client ID:");
        String clientId = scanner.nextLine().trim();
        if (clientId.isEmpty()) clientId = "console-producer-" + System.currentTimeMillis();

        System.out.println("Enter topic name:");
        String topic = scanner.nextLine().trim();
        if (topic.isEmpty()) topic = Constant.TEST_TOPIC;

        System.out.println("Enter partition (default: 0):");
        int partition = 0;
        try {
            String partitionStr = scanner.nextLine().trim();
            if (!partitionStr.isEmpty()) partition = Integer.parseInt(partitionStr);
        } catch (NumberFormatException e) {
            System.out.println("Invalid partition, using default 0");
        }

        MQProducer producer = new MQProducer(host, port, clientId);
        producer.connect();

        System.out.println("\nEnter messages or 'exit' to quit:");
        while (true) {
            System.out.print("> ");
            String message = scanner.nextLine().trim();
            if ("exit".equalsIgnoreCase(message)) {
                break;
            }
            if (!message.isEmpty()) {
                try {
                    producer.send(topic, partition, message.getBytes());
                    System.out.println("Sent to " + topic + ":" + partition + " - " + message);
                } catch (Exception e) {
                    System.err.println("Send failed: " + e.getMessage());
                }
            }
        }

        producer.close();
        scanner.close();
        System.out.println("Producer exited.");
    }
}
